package com.feeyin.radar.crm.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.web.multipart.MultipartFile;

import com.feeyin.radar.commons.DateUtils;
import com.feeyin.radar.commons.ExcelUtils;
import com.feeyin.radar.commons.FileUtils;
import com.feeyin.radar.commons.Log;
import com.feeyin.radar.commons.NumberUtils;
import com.feeyin.radar.commons.Page;
import com.feeyin.radar.commons.StringUtils;
import com.feeyin.radar.crm.dao.ContractCaseDAO;
import com.feeyin.radar.crm.dao.ContractDAO;
import com.feeyin.radar.crm.dao.ContractDetailDAO;
import com.feeyin.radar.crm.dao.ContractDetailTempDAO;
import com.feeyin.radar.crm.dao.ContractDetailUpdateHistoryDAO;
import com.feeyin.radar.crm.dao.ContractInvoiceDAO;
import com.feeyin.radar.crm.dao.ContractTempDAO;
import com.feeyin.radar.crm.dao.ContractUpdateHistoryDAO;
import com.feeyin.radar.crm.dao.CustomerDAO;
import com.feeyin.radar.crm.dao.CustomerShareDAO;
import com.feeyin.radar.crm.dao.SaleRecordDAO;
import com.feeyin.radar.crm.dao.SystemFileDAO;
import com.feeyin.radar.crm.form.ContractCaseForm;
import com.feeyin.radar.crm.form.ContractForm;
import com.feeyin.radar.crm.form.CostForm;
import com.feeyin.radar.crm.form.UploadFileForm;
import com.feeyin.radar.crm.model.CodeStore;
import com.feeyin.radar.crm.model.Contract;
import com.feeyin.radar.crm.model.ContractCase;
import com.feeyin.radar.crm.model.ContractDetail;
import com.feeyin.radar.crm.model.CostManage;
import com.feeyin.radar.crm.model.Customer;
import com.feeyin.radar.crm.model.QueryContract;
import com.feeyin.radar.crm.model.SystemFile;
import com.feeyin.radar.crm.service.ContractService;
import com.feeyin.radar.msg.dao.WarningInfoDAO;
import com.feeyin.radar.sys.dao.DepartmentDAO;
import com.feeyin.radar.sys.dao.UserDAO;
import com.feeyin.radar.sys.model.Users;

public class ContractServiceImpl
  implements ContractService
{
  private ContractDAO contractDAO;
  private ContractCaseDAO contractCaseDAO;
  private ContractDetailDAO contractDetailDAO;
  private SystemFileDAO systemFileDAO;
  private CustomerShareDAO customerShareDAO;
  private CustomerDAO customerDAO;
  private UserDAO userDAO;
  private DepartmentDAO departmentDAO;
  private ContractUpdateHistoryDAO contractUpdateHistoryDAO;
  private ContractDetailUpdateHistoryDAO contractDetailUpdateHistoryDAO;
  private ContractTempDAO contractTempDAO;
  private ContractDetailTempDAO contractDetailTempDAO;
  private ContractInvoiceDAO contractInvoiceDAO;
  private WarningInfoDAO warningInfoDAO;
  private SaleRecordDAO saleRecordDAO;
  

  public ContractCaseDAO getContractCaseDAO() {
	return contractCaseDAO;
}

public void setContractCaseDAO(ContractCaseDAO contractCaseDAO) {
	this.contractCaseDAO = contractCaseDAO;
}

public ContractDAO getContractDAO()
  {
    return this.contractDAO;
  }

  public void setContractDAO(ContractDAO contractDAO) {
    this.contractDAO = contractDAO;
  }

  public ContractDetailDAO getContractDetailDAO() {
    return this.contractDetailDAO;
  }

  public void setContractDetailDAO(ContractDetailDAO contractDetailDAO) {
    this.contractDetailDAO = contractDetailDAO;
  }

  public SystemFileDAO getSystemFileDAO() {
    return this.systemFileDAO;
  }

  public void setSystemFileDAO(SystemFileDAO systemFileDAO) {
    this.systemFileDAO = systemFileDAO;
  }

  public CustomerShareDAO getCustomerShareDAO() {
    return this.customerShareDAO;
  }

  public void setCustomerShareDAO(CustomerShareDAO customerShareDAO) {
    this.customerShareDAO = customerShareDAO;
  }

  public CustomerDAO getCustomerDAO() {
    return this.customerDAO;
  }

  public void setCustomerDAO(CustomerDAO customerDAO) {
    this.customerDAO = customerDAO;
  }

  public UserDAO getUserDAO() {
    return this.userDAO;
  }

  public void setUserDAO(UserDAO userDAO) {
    this.userDAO = userDAO;
  }

  public DepartmentDAO getDepartmentDAO() {
    return this.departmentDAO;
  }

  public void setDepartmentDAO(DepartmentDAO departmentDAO) {
    this.departmentDAO = departmentDAO;
  }

  public ContractUpdateHistoryDAO getContractUpdateHistoryDAO() {
    return this.contractUpdateHistoryDAO;
  }

  public void setContractUpdateHistoryDAO(ContractUpdateHistoryDAO contractUpdateHistoryDAO)
  {
    this.contractUpdateHistoryDAO = contractUpdateHistoryDAO;
  }

  public ContractDetailUpdateHistoryDAO getContractDetailUpdateHistoryDAO() {
    return this.contractDetailUpdateHistoryDAO;
  }

  public void setContractDetailUpdateHistoryDAO(ContractDetailUpdateHistoryDAO contractDetailUpdateHistoryDAO)
  {
    this.contractDetailUpdateHistoryDAO = contractDetailUpdateHistoryDAO;
  }

  public ContractTempDAO getContractTempDAO() {
    return this.contractTempDAO;
  }

  public void setContractTempDAO(ContractTempDAO contractTempDAO) {
    this.contractTempDAO = contractTempDAO;
  }

  public ContractDetailTempDAO getContractDetailTempDAO() {
    return this.contractDetailTempDAO;
  }

  public void setContractDetailTempDAO(ContractDetailTempDAO contractDetailTempDAO) {
    this.contractDetailTempDAO = contractDetailTempDAO;
  }

  public ContractInvoiceDAO getContractInvoiceDAO() {
    return this.contractInvoiceDAO;
  }

  public void setContractInvoiceDAO(ContractInvoiceDAO contractInvoiceDAO) {
    this.contractInvoiceDAO = contractInvoiceDAO;
  }

  public WarningInfoDAO getWarningInfoDAO() {
    return this.warningInfoDAO;
  }

  public void setWarningInfoDAO(WarningInfoDAO warningInfoDAO) {
    this.warningInfoDAO = warningInfoDAO;
  }

  public SaleRecordDAO getSaleRecordDAO() {
    return this.saleRecordDAO;
  }

  public void setSaleRecordDAO(SaleRecordDAO saleRecordDAO) {
    this.saleRecordDAO = saleRecordDAO;
  }

  public List getPageDeptContracts(String customerName, Integer currentUserId, Page page, QueryContract queryContract)
  {
    if (currentUserId == null) return null;
    if (page == null) return null;
    Users user = new Users();
    user = this.userDAO.getUser(currentUserId);
    if ((user == null) || (user.getDeptId() == null)) return null;
    String deptIds = "";
    deptIds = this.departmentDAO.getCurrentDeptIdAndSubDeptIdsByDeptId(user.getDeptId());
    if (StringUtils.isEmpty(deptIds)) return null;

    Contract contract = new Contract();

    contract.setMoreStatus("2,4");
    contract.setDeptIds(deptIds);
    if (!StringUtils.isEmpty(customerName)) {
      contract.setCustomerName(customerName);
    }

    if (queryContract != null) {
      if (!StringUtils.isEmpty(queryContract.getContractCode())) {
        contract.setContractCode(queryContract.getContractCode());
      }
      if (queryContract.getSalePersonId() != null) {
        contract.setSalePersonId(queryContract.getSalePersonId());
      }
      if (!StringUtils.isEmpty(queryContract.getCustomerName2())) {
        contract.setCustomerName(queryContract.getCustomerName2());
      }
      if ((queryContract.getStartContractCost() != null) && (queryContract.getStartContractCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndContractCost() != null) && (queryContract.getEndContractCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartContractCost(queryContract.getStartContractCost());
        contract.setEndContractCost(queryContract.getEndContractCost());
      }
      if (!StringUtils.isEmpty(queryContract.getPurchaseDesc())) {
        contract.setPurchaseDesc(queryContract.getPurchaseDesc());
      }
      if ((queryContract.getStartContractDate() != null) && (queryContract.getEndContractDate() != null)) {
        contract.setStartDate(queryContract.getStartContractDate());
        contract.setEndDate(queryContract.getEndContractDate());
      }
      if ((queryContract.getStartBackCost() != null) && (queryContract.getStartBackCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndBackCost() != null) && (queryContract.getEndBackCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartBackCost(queryContract.getStartBackCost());
        contract.setEndBackCost(queryContract.getEndBackCost());
      }
      if (!StringUtils.isEmpty(queryContract.getInvoiceDesc())) {
        contract.setInvoiceDesc(queryContract.getInvoiceDesc());
      }
    }

    List contracts = new ArrayList();
    contracts = this.contractDAO.getPageContractsByDynamic(contract, page);
    if (contracts == null) return null;
    for (int i = 0; i < contracts.size(); i++) {
      contract = new Contract();
      contract = (Contract)contracts.get(i);
      Customer customer = new Customer();
      customer = this.customerDAO.getCustomerById(contract.getCustomerId());
      if (customer != null) {
        contract.setCustomerName(customer.getCustomerName());
      }
      user = new Users();
      user = this.userDAO.getUser(contract.getSalePersonId());
      if (user != null) {
        contract.setSalePerson(user.getUserName());
      }
    }
    return contracts;
  }

  public Integer getPageDetpContractsCount(String customerName, Integer currentUserId, QueryContract queryContract)
  {
    if (currentUserId == null) return null;
    Users user = new Users();
    user = this.userDAO.getUser(currentUserId);
    if ((user == null) || (user.getDeptId() == null)) return null;
    String deptIds = "";
    deptIds = this.departmentDAO.getCurrentDeptIdAndSubDeptIdsByDeptId(user.getDeptId());
    if (StringUtils.isEmpty(deptIds)) return null;

    Contract contract = new Contract();

    contract.setMoreStatus("2,4");
    contract.setDeptIds(deptIds);
    if (!StringUtils.isEmpty(customerName)) {
      contract.setCustomerName(customerName);
    }

    if (queryContract != null) {
      if (!StringUtils.isEmpty(queryContract.getContractCode())) {
        contract.setContractCode(queryContract.getContractCode());
      }
      if (!StringUtils.isEmpty(queryContract.getCustomerName2())) {
        contract.setCustomerName(queryContract.getCustomerName2());
      }
      if (queryContract.getSalePersonId() != null) {
        contract.setSalePersonId(queryContract.getSalePersonId());
      }
      if ((queryContract.getStartContractCost() != null) && (queryContract.getStartContractCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndContractCost() != null) && (queryContract.getEndContractCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartContractCost(queryContract.getStartContractCost());
        contract.setEndContractCost(queryContract.getEndContractCost());
      }
      if (!StringUtils.isEmpty(queryContract.getPurchaseDesc())) {
        contract.setPurchaseDesc(queryContract.getPurchaseDesc());
      }
      if ((queryContract.getStartContractDate() != null) && (queryContract.getEndContractDate() != null)) {
        contract.setStartDate(queryContract.getStartContractDate());
        contract.setEndDate(queryContract.getEndContractDate());
      }
      if ((queryContract.getStartBackCost() != null) && (queryContract.getStartBackCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndBackCost() != null) && (queryContract.getEndBackCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartBackCost(queryContract.getStartBackCost());
        contract.setEndBackCost(queryContract.getEndBackCost());
      }
      if (!StringUtils.isEmpty(queryContract.getInvoiceDesc())) {
        contract.setInvoiceDesc(queryContract.getInvoiceDesc());
      }
    }

    return this.contractDAO.getPageContractsCountByDynamic(contract);
  }

  public List getPageMyContracts(String isImportContract, String status, String customerName, Integer currentUserId, Page page, QueryContract queryContract)
  {
    if (StringUtils.isEmpty(status)) return null;
    if (currentUserId == null) return null;
    if (page == null) return null;
    Contract contract = new Contract();
    contract.setStatus(status);
    if ((StringUtils.isEmpty(isImportContract)) || (!"1".equals(isImportContract)))
    {
      contract.setSalePersonId(currentUserId);
    }
    if (!StringUtils.isEmpty(customerName)) {
      contract.setCustomerName(customerName);
    }

    if (queryContract != null) {
      if (!StringUtils.isEmpty(queryContract.getContractCode())) {
        contract.setContractCode(queryContract.getContractCode());
      }
      if (!StringUtils.isEmpty(queryContract.getCustomerName2())) {
        contract.setCustomerName(queryContract.getCustomerName2());
      }
      if ((queryContract.getStartContractCost() != null) && (queryContract.getStartContractCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndContractCost() != null) && (queryContract.getEndContractCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartContractCost(queryContract.getStartContractCost());
        contract.setEndContractCost(queryContract.getEndContractCost());
      }
      if (queryContract.getSalePersonId() != null) {
        contract.setSalePersonId(queryContract.getSalePersonId());
      }
      if (!StringUtils.isEmpty(queryContract.getPurchaseDesc())) {
        contract.setPurchaseDesc(queryContract.getPurchaseDesc());
      }
      if ((queryContract.getStartContractDate() != null) && (queryContract.getEndContractDate() != null)) {
        contract.setStartDate(queryContract.getStartContractDate());
        contract.setEndDate(queryContract.getEndContractDate());
      }
      if ((queryContract.getStartBackCost() != null) && (queryContract.getStartBackCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndBackCost() != null) && (queryContract.getEndBackCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartBackCost(queryContract.getStartBackCost());
        contract.setEndBackCost(queryContract.getEndBackCost());
      }
      if (!StringUtils.isEmpty(queryContract.getInvoiceDesc())) {
        contract.setInvoiceDesc(queryContract.getInvoiceDesc());
      }
    }

    List contracts = new ArrayList();
    contracts = this.contractDAO.getPageContractsByDynamic(contract, page);
    if (contracts == null) return null;
    for (int i = 0; i < contracts.size(); i++) {
      contract = new Contract();
      contract = (Contract)contracts.get(i);
      Customer customer = new Customer();
      customer = this.customerDAO.getCustomerById(contract.getCustomerId());
      if (customer != null) {
        contract.setCustomerName(customer.getCustomerName());
      }
      Users user = new Users();
      user = this.userDAO.getUser(contract.getSalePersonId());
      if (user != null) {
        contract.setSalePerson(user.getUserName());
      }

      user = new Users();
      user = this.userDAO.getUser(contract.getAuditPersonId());
      if (user != null) {
        contract.setAuditPerson(user.getUserName());
      }

    }

    return contracts;
  }

  public Integer getPageMyContractsCount(String isImportContract, String status, String customerName, Integer currentUserId, QueryContract queryContract) {
    if (StringUtils.isEmpty(status)) return null;
    if (currentUserId == null) return null;
    Contract contract = new Contract();
    contract.setStatus(status);
    if ((StringUtils.isEmpty(isImportContract)) || (!"1".equals(isImportContract)))
    {
      contract.setSalePersonId(currentUserId);
    }
    if (!StringUtils.isEmpty(customerName)) {
      contract.setCustomerName(customerName);
    }

    if (queryContract != null) {
      if (!StringUtils.isEmpty(queryContract.getContractCode())) {
        contract.setContractCode(queryContract.getContractCode());
      }
      if (!StringUtils.isEmpty(queryContract.getCustomerName2())) {
        contract.setCustomerName(queryContract.getCustomerName2());
      }
      if ((queryContract.getStartContractCost() != null) && (queryContract.getStartContractCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndContractCost() != null) && (queryContract.getEndContractCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartContractCost(queryContract.getStartContractCost());
        contract.setEndContractCost(queryContract.getEndContractCost());
      }
      if (queryContract.getSalePersonId() != null) {
        contract.setSalePersonId(queryContract.getSalePersonId());
      }
      if (!StringUtils.isEmpty(queryContract.getPurchaseDesc())) {
        contract.setPurchaseDesc(queryContract.getPurchaseDesc());
      }
      if ((queryContract.getStartContractDate() != null) && (queryContract.getEndContractDate() != null)) {
        contract.setStartDate(queryContract.getStartContractDate());
        contract.setEndDate(queryContract.getEndContractDate());
      }
      if ((queryContract.getStartBackCost() != null) && (queryContract.getStartBackCost().compareTo(new BigDecimal(0)) > 0) && 
        (queryContract.getEndBackCost() != null) && (queryContract.getEndBackCost().compareTo(new BigDecimal(0)) > 0)) {
        contract.setStartBackCost(queryContract.getStartBackCost());
        contract.setEndBackCost(queryContract.getEndBackCost());
      }
      if (!StringUtils.isEmpty(queryContract.getInvoiceDesc())) {
        contract.setInvoiceDesc(queryContract.getInvoiceDesc());
      }
    }

    return this.contractDAO.getPageContractsCountByDynamic(contract);
  }

  public Contract getContractById(Integer id) {
    if (id == null) return null;
    Contract contract = new Contract();
    contract = this.contractDAO.getContractById(id);
    if (contract == null) return null;

    Customer customer = new Customer();
    customer = this.customerDAO.getCustomerById(contract.getCustomerId());
    if (customer != null) {
      contract.setCustomerName(customer.getCustomerName());
    }

    Users user = new Users();
    user = this.userDAO.getUser(contract.getSalePersonId());
    if (user != null) {
      contract.setSalePerson(user.getUserName());
    }

    user = new Users();
    user = this.userDAO.getUser(contract.getAuditPersonId());
    if (user != null) {
      contract.setAuditPerson(user.getUserName());
    }

    return contract;
  }

  public List getContractAddedsById(String realPath, Integer id) {
    if (id == null) return null;
    if (StringUtils.isEmpty(realPath)) return null;
    Contract contract = new Contract();
    contract = this.contractDAO.getContractById(id);
    if (contract == null) return null;

    List systemFiles = new ArrayList();
    systemFiles = this.systemFileDAO.getSystemFilesByRelatedId(id);
    if (systemFiles != null) {
      for (int i = 0; i < systemFiles.size(); i++) {
        SystemFile systemFile = new SystemFile();
        systemFile = (SystemFile)systemFiles.get(i);
        systemFile.setPerson(this.userDAO.getUserNameById(systemFile.getPersonId()));
        if (isFileExists(null, realPath + systemFile.getPath(), contract.getCustomerId(), id, systemFile.getFileName())) {
          contract.getSystemFiles().add(systemFile);
        }
      }
    }
    return contract.getSystemFiles();
  }

  public List getContractDetailsByContractId(Integer contractId) {
    if (contractId == null) return null;
    List contractDetails = new ArrayList();
    contractDetails = this.contractDetailDAO.getContractDetailsByContractId(contractId);
    return contractDetails;
  }

  public List getContractDetailUpdateHistorysByContractId(Integer contractId) {
    if (contractId == null) return null;
    return this.contractDetailUpdateHistoryDAO.getContractDetailUpdateHistorysByContractId(contractId);
  }

  public boolean isExistContractTemp(Integer contractId) {
    if (contractId == null) return false;
    Contract contractTemp = new Contract();
    contractTemp = this.contractTempDAO.getContractTempByContractId(contractId);
    return contractTemp != null;
  }

  public boolean isRepeatAddContract(String contractCode)
  {
    if (StringUtils.isEmpty(contractCode)) return false;
    return this.contractDAO.getContractByContractCode(contractCode) != null;
  }

  public boolean isRepeatUpdateContract(Integer id, String contractCode)
  {
    if (id == null) return false;
    if (StringUtils.isEmpty(contractCode)) return false;
    Contract oldContract = new Contract();
    oldContract = this.contractDAO.getContractById(id);
    if (oldContract == null) return false;
    if (contractCode.equals(oldContract.getContractCode())) return false;
    return this.contractDAO.getContractByContractCode(contractCode) != null;
  }

  public List importContract(Integer userId, UploadFileForm uploadFileForm, String realPath, MultipartFile multipartFile)
  {
    boolean result1 = false;
    boolean result2 = false;

    String fileName = multipartFile.getOriginalFilename();
    String basePath = realPath + "upload" + System.getProperty("file.separator") + "temp";
    String storedPath = basePath + System.getProperty("file.separator") + fileName;
    result1 = FileUtils.saveFile(storedPath, multipartFile);

    List logs = new ArrayList();
    if (result1) {
      logs = readExcelContractContent(storedPath, userId);
    }

    return logs;
  }

  public boolean insertContract(ContractForm contractForm, String realPath, MultipartFile multipartFile)
  {
		if(contractForm == null)return false;
		if(contractForm.getCustomerId() == null)return false;
//		if(contractForm.getPurchaseDesc() == null 
//				|| contractForm.getPurchaseDesc().length <= 0)return false;
		
		BigDecimal contractCost = new BigDecimal(0);
		//å�ˆå�Œè¡¨
		Contract contract = new Contract();
		contract.setCustomerId(contractForm.getCustomerId());
		contract.setContractCode(contractForm.getContractCode());
		contract.setContractName(contractForm.getContractName());
		contract.setContractCost(contractCost);
		contract.setBackCost(new BigDecimal(0));
		contract.setReceivable(contractCost);
		contract.setContractDate(contractForm.getContractDate());
		if(contractForm.getSalePersonId() != null){
			contract.setSalePersonId(contractForm.getSalePersonId());
		}else{
			contract.setSalePersonId(contractForm.getApplyPersonId());
		}
		contract.setCreateDate(new Date());
		contract.setStatus("1");//å¾…å®¡æ ¸
		contract.setApplyPersonId(contractForm.getApplyPersonId());
		contract.setBackCostNum(0);
		contract.setAging(0);
		contract.setContractDesc(contractForm.getContractDesc());
	
		List<ContractCase> caseList = packContractCase(contractForm);
		contract.setContractCaseList(caseList);
		contractDAO.insertContract(contract);
		Contract newContract = new Contract();
		newContract = contractDAO.getContractByContractCode(contractForm.getContractCode());
		if(newContract == null)return false;
		Integer contractId = newContract.getId();//test
		insertContractUpdateHistory(newContract, newContract.getApplyPersonId(), 0);
		
		Contract paraContract = new Contract();
		paraContract.setId(contractId);
		paraContract.setContractCost(contractCost);
		paraContract.setReceivable(contractCost);
		contractDAO.updateContractByDynamic(paraContract);

		if(!StringUtils.isEmpty(realPath) 
				&& multipartFile != null && !multipartFile.isEmpty()){
			String fileName = multipartFile.getOriginalFilename();//å¾—åˆ°æ–‡ä»¶å��
			String storedPath = getStoredPath(realPath, newContract.getCustomerId(),contractId) 
									+ System.getProperty("file.separator") + fileName;
			boolean result2 = false;
			result2 = FileUtils.saveFile(storedPath, multipartFile);
			if(result2){
				SystemFile systemFile = new SystemFile();
				systemFile.setFileName(fileName);
				systemFile.setFileType(multipartFile.getContentType());
				//å­˜ç›¸å¯¹è·¯å¾„
				systemFile.setPath(getStoredRelativePath(newContract.getCustomerId(),contractId) + System.getProperty("file.separator"));
				systemFile.setPersonId(newContract.getApplyPersonId());
				systemFile.setRelatedId(contractId);
				systemFile.setRelatedTable("contract");
				systemFile.setSize(multipartFile.getSize() + "");
				systemFile.setUploadDate(new Date());
				systemFileDAO.insertSystemFile(systemFile);
			}
		}
		
		Customer customer = new Customer();
		customer = customerDAO.getCustomerById(newContract.getCustomerId());
		if(customer != null){
			Customer paraCustomer = new Customer();
			paraCustomer.setId(customer.getId());
			paraCustomer.setIsFollow("0");
			paraCustomer.setIsShare("0");
			paraCustomer.setUpdateSaleStageDate(new Date());

			paraCustomer.setSaleStageId(0);
			paraCustomer.setPredictCost(new BigDecimal(0));
			paraCustomer.setPredictContract(null);
			paraCustomer.setSaleStatus("3");
			customerDAO.updateCustomer(paraCustomer);
			customerShareDAO.deleteCustomerShare(customer.getId());
			customerShareDAO.insertCustomerShare(customer.getId(), customer.getSalePersonId(), "1");
			
			saleRecordDAO.updateSaleRecordStatusByCustomerId(customer.getId(), "0", "1");
			saleRecordDAO.deleteSaleRecordByCustomerIdAndStatus(customer.getId(), "3");
		}
		
		warningInfoDAO.insertAuditWarningInfoForContract(newContract);
		
		return true;
  }
  
  public boolean insertContractCase(ContractCaseForm contractCaseForm, String paramString, MultipartFile paramMultipartFile)
  {
	  ContractCase cc = insertContractCase(contractCaseForm); 
	  contractDAO.insertContractCase(cc);
	  return true;
  }
  
  	public List<ContractCase> packContractCase(ContractForm contractForm)
	{
  		List<ContractCase> list = new ArrayList<ContractCase>();
  		if(contractForm.getProcessName()!=null&&contractForm.getProcessName().length>0){
  			for(int i=0;i<contractForm.getProcessName().length;i++){
  				ContractCase cc = new ContractCase();
  				cc.setSuffixCaseName(contractForm.getSuffixCaseName()[i]==null?"":contractForm.getSuffixCaseName()[i]);
  				cc.setCostValue(contractForm.getCostValue()[i].doubleValue());
  				if(contractForm.getContractCaseName().length<i+1)
  					cc.setPrefixCaseName("");
  				else
  				    cc.setPrefixCaseName(contractForm.getContractCaseName()[i]==null?"":contractForm.getContractCaseName()[i]);
  				if(contractForm.getApplicationCode().length<i+1)
  					cc.setApplicationCode("");
  				else
  	  			    cc.setApplicationCode(contractForm.getApplicationCode()[i]==null?"":contractForm.getApplicationCode()[i]);
  				if(contractForm.getCaseCode().length<i+1)
  					cc.setCaseCode("");
  				else
  				    cc.setCaseCode(contractForm.getCaseCode()[i]==null?"":contractForm.getCaseCode()[i]);
  				if(contractForm.getDescription().length<i+1)
  					cc.setDescription("");
  				else
  	  			    cc.setDescription(contractForm.getDescription()[i]==null?"":contractForm.getDescription()[i]);
  	  		    if(contractForm.getTypeId().length<i+1)
  	  			   cc.setType("");
  	  		    else
  	  			   cc.setType(contractForm.getTypeId()[i]==null?"":contractForm.getTypeId()[i]);
  	  			cc.setDiscount(contractForm.getCaseDiscount());
  	  			cc.setProxyCost(contractForm.getProxyCost()[i]==null?0D:contractForm.getProxyCost()[i]);
  	  			cc.setOfficialCost(contractForm.getOfficialCost()[i]==null?0D:contractForm.getOfficialCost()[i]);
  	  			cc.setOperationCost(contractForm.getOperationCost()[i]==null?0D:contractForm.getOperationCost()[i]);
  	  			
  	  		    if(contractForm.getTypeId().length<i+1)
  	  		      cc.setApplicationDate(new Date());
	  		    else
	  		      cc.setApplicationDate(contractForm.getApplicationDate()[i]==null?new Date():contractForm.getApplicationDate()[i]);
  	  		    
  	  		    if(contractForm.getCaseId().length<i+1)
 	  		      cc.setId(null);
	  		    else
	  		     cc.setId(contractForm.getCaseId()[i]==null?null:contractForm.getCaseId()[i]);
  	
  	  			cc.setMark(contractForm.getMark()[i]==null?"":contractForm.getMark()[i]);
  	  			if(contractForm.getProcessId().length<i+1)
  	  			   cc.setProcessId(0);
  	  			else
  	  			   cc.setProcessId(contractForm.getProcessId()[i]);
  	  			if(contractForm.getProcessGroupId().length<i+1)
  	  			   cc.setProcessGroupId(0);
  	  			else
  	  			    cc.setProcessGroupId(contractForm.getProcessGroupId()[i]);
  	  		    if(contractForm.getAttachId().length<i+1)
	  			   cc.setAttachId(null);
	  			else
	  			    cc.setAttachId(contractForm.getAttachId()[i]==null ?null:Long.valueOf(contractForm.getAttachId()[i]));
  	  			//cc.setModifyDate(contractForm.getModifyDate());
  	  		list.add(cc);
  			}
  		}
		
		
		return list;
		
	}  

  	public ContractCase insertContractCase(ContractCaseForm contractCaseForm)
	{
		ContractCase cc = new ContractCase();
		cc.setApplicationCode(contractCaseForm.getApplicationCode());
		cc.setCaseCode(contractCaseForm.getCaseCode());
		cc.setCostValue(contractCaseForm.getCostCaseValue());
		cc.setDescription(contractCaseForm.getDescription());
		cc.setType(contractCaseForm.getTypeId());
		cc.setDiscount(contractCaseForm.getCaseDiscount());
		cc.setProxyCost(contractCaseForm.getProxyCost());
		cc.setOfficialCost(contractCaseForm.getOfficialCost());
		cc.setOperationCost(contractCaseForm.getOperationCost());
		cc.setApplicationDate(contractCaseForm.getApplicationDate());
		
		cc.setProcessId(contractCaseForm.getProcessId());
		cc.setProcessGroupId(contractCaseForm.getProcessGroupId());
		cc.setModifyDate(contractCaseForm.getModifyDate());
		
		return cc;
		
	}  	
  	
  public boolean updateContract(ContractForm contractForm, String realPath, MultipartFile multipartFile, Integer userId)
  {
    if (contractForm == null) return false;
    if (contractForm.getId() == null) return false;

//    if ((contractForm.getPurchaseDesc() == null) || 
//      (contractForm.getPurchaseDesc().length <= 0)) return false;

    insertContractTemp(contractForm.getId());

    BigDecimal contractCost = new BigDecimal(0);

    Contract contract = new Contract();
    contract.setId(contractForm.getId());
    contract.setContractCode(contractForm.getContractCode());
    contract.setContractName(contractForm.getContractName());
    contract.setContractDate(contractForm.getContractDate());
    contract.setSalePersonId(contractForm.getSalePersonId());
    contract.setStatus("1");
    contract.setUpdateReason(contractForm.getUpdateReason());
    contract.setContractDesc(contractForm.getContractDesc());
    this.contractDAO.updateContractByDynamic(contract);
    Contract newContract = new Contract();
    newContract = this.contractDAO.getContractById(contractForm.getId());
    if (newContract == null) return false;

    Integer contractId = newContract.getId();

    insertContractUpdateHistory(newContract, userId, 1);

//    boolean deleteSuccess = false;
//    deleteSuccess = this.contractDetailDAO.deleteContractDetail(contractId);
//    if (deleteSuccess)
//    {
//      String updateHistoryCode = new Long(new Date().getTime()).toString();
//      int num = 0;
//      for (int i = 0; i < contractForm.getPurchaseDesc().length; i++) {
//        if (!StringUtils.isEmpty(contractForm.getPurchaseDesc()[i])) {
//          ContractDetail contractDetail = new ContractDetail();
//          contractDetail.setContractId(contractId);
//          contractDetail.setDetailCode(num + 1+"");
//          contractDetail.setPurchaseDesc(contractForm.getPurchaseDesc()[i]);
//          if ((contractForm.getUnit() != null) && (contractForm.getUnit().length > 0)) {
//            contractDetail.setUnit(contractForm.getUnit()[i]);
//          }
//          if ((contractForm.getPrice() != null) && (contractForm.getPrice().length > 0)) {
//            contractDetail.setPrice(contractForm.getPrice()[i]);
//          }
//          if ((contractForm.getNum() != null) && (contractForm.getNum().length > 0)) {
//            contractDetail.setNum(contractForm.getNum()[i]);
//          }
//          if ((contractForm.getCostValue() != null) && (contractForm.getCostValue().length > 0)) {
//            contractDetail.setCostValue(contractForm.getCostValue()[i]);
//            contractCost = contractCost.add(contractForm.getCostValue()[i]);
//          }
//          if ((contractForm.getDiscount() != null) && (contractForm.getDiscount().length > 0)) {
//            contractDetail.setDiscount(contractForm.getDiscount()[i]);
//          }
//          if ((contractForm.getCosts() != null) && (contractForm.getCosts().length > 0)) {
//            contractDetail.setCosts(contractForm.getCosts()[i]);
//          }
//          if ((contractForm.getProssProfit() != null) && (contractForm.getProssProfit().length > 0)) {
//            contractDetail.setProssProfit(contractForm.getProssProfit()[i]);
//          }
//          this.contractDetailDAO.insertContractDetail(contractDetail);
//
//          insertContractDetailUpdateHistory(updateHistoryCode, contractDetail, 1);
//          num++;
//        }
//      }
//
//    }

    Contract paraContract = new Contract();
    paraContract.setId(contractId);
    paraContract.setContractCost(contractCost);
    if (newContract.getBackCost() != null) {
      paraContract.setReceivable(contractCost.subtract(newContract.getBackCost()));
    }
    this.contractDAO.updateContractByDynamic(paraContract);

    List<ContractCase> contractCases  = packContractCase(contractForm);
   // contractCaseDAO.delCaseList(paraContract.getId().longValue());
    this.contractCaseDAO.saveContractCase(contractCases, paraContract.getId().longValue());
    
    if ((!StringUtils.isEmpty(realPath)) && 
      (multipartFile != null) && (!multipartFile.isEmpty())) {
      String fileName = multipartFile.getOriginalFilename();
      String storedPath = getStoredPath(realPath, newContract.getCustomerId(), contractId) + 
        System.getProperty("file.separator") + fileName;
      boolean result2 = false;
      result2 = FileUtils.saveFile(storedPath, multipartFile);
      if (result2) {
        SystemFile systemFile = new SystemFile();
        systemFile.setFileName(fileName);
        systemFile.setFileType(multipartFile.getContentType());

        systemFile.setPath(getStoredRelativePath(newContract.getCustomerId(), contractId) + System.getProperty("file.separator"));
        systemFile.setPersonId(newContract.getApplyPersonId());
        systemFile.setRelatedId(contractId);
        systemFile.setRelatedTable("contract");
        systemFile.setSize(multipartFile.getSize()+"");
        systemFile.setUploadDate(new Date());
        this.systemFileDAO.insertSystemFile(systemFile);
      }

    }

    this.warningInfoDAO.insertAuditWarningInfoForContract(newContract);
    return true;
  }

  public String updateAllContractAging(String updateAgingDate) {
    String strCurDate = DateUtils.getStringDateByFormat(new Date(), "yyyy-MM-dd");
    if ((!StringUtils.isEmpty(updateAgingDate)) && (strCurDate.equals(updateAgingDate))) return null;
    List contracts = new ArrayList();
    contracts = this.contractDAO.getAllContracts();
    if ((contracts != null) && (contracts.size() > 0)) {
      for (int i = 0; i < contracts.size(); i++) {
        Contract contract = new Contract();
        contract = (Contract)contracts.get(i);
        if (!"4".equals(contract.getStatus())) {
          Date invoiceDate = this.contractInvoiceDAO.getMinInvoiceDate(contract.getId());
          Contract paraContract = new Contract();
          paraContract.setId(contract.getId());
          paraContract.setAging(Integer.valueOf(Integer.parseInt(Long.valueOf(DateUtils.getDayByDate(invoiceDate)).toString())));
          this.contractDAO.updateContractByDynamic(paraContract);
        }
      }
      return strCurDate;
    }
    return null;
  }

  public boolean stopContract(ContractForm contractForm, String realPath, MultipartFile multipartFile)
  {
    if (contractForm == null) return false;
    if (contractForm.getId() == null) return false;

    Contract contract = new Contract();
    contract.setId(contractForm.getId());
    contract.setStatus("4");
    contract.setStopReason(contractForm.getStopReason());
    contract.setReceivable(new BigDecimal(0));
    this.contractDAO.updateContractByDynamic(contract);
    Contract newContract = new Contract();
    newContract = this.contractDAO.getContractById(contractForm.getId());
    if (newContract == null) return false;

    if ((!StringUtils.isEmpty(realPath)) && 
      (multipartFile != null) && (!multipartFile.isEmpty())) {
      String fileName = multipartFile.getOriginalFilename();
      String storedPath = getStoredPath(realPath, newContract.getCustomerId(), newContract.getId()) + 
        System.getProperty("file.separator") + fileName;
      boolean result2 = false;
      result2 = FileUtils.saveFile(storedPath, multipartFile);
      if (result2) {
        SystemFile systemFile = new SystemFile();
        systemFile.setFileName(fileName);
        systemFile.setFileType(multipartFile.getContentType());

        systemFile.setPath(getStoredRelativePath(newContract.getCustomerId(), newContract.getId()) + System.getProperty("file.separator"));
        systemFile.setPersonId(newContract.getApplyPersonId());
        systemFile.setRelatedId(newContract.getId());
        systemFile.setRelatedTable("contract");
        systemFile.setSize(multipartFile.getSize()+"");
        systemFile.setUploadDate(new Date());
        this.systemFileDAO.insertSystemFile(systemFile);
      }
    }
    return true;
  }

  public boolean cancelContract(ContractForm contractForm, String realPath, MultipartFile multipartFile)
  {
    if (contractForm == null) return false;
    if (contractForm.getId() == null) return false;

    Contract contractTemp = new Contract();
    List contractDetailTemps = new ArrayList();
    contractTemp = this.contractTempDAO.getContractTempByContractId(contractForm.getId());
    contractDetailTemps = this.contractDetailTempDAO.getContractDetailTempsByContractId(contractForm.getId());
    if ((contractTemp != null) && ((contractDetailTemps != null) || (contractDetailTemps.size() > 0)))
    {
      BigDecimal contractCost = new BigDecimal(0);

      Contract contract = new Contract();
      contract.setId(contractForm.getId());
      contract.setContractCode(contractTemp.getContractCode());
      contract.setContractDate(contractTemp.getContractDate());
      contract.setSalePersonId(contractTemp.getSalePersonId());
      contract.setStatus(contractTemp.getStatus());
      contract.setUpdateReason(contractTemp.getUpdateReason());
      contract.setStopReason(contractForm.getStopReason());
      this.contractDAO.updateContractByDynamic(contract);
      Contract newContract = new Contract();
      newContract = this.contractDAO.getContractById(contractForm.getId());
      if (newContract == null) return false;

      this.contractDetailDAO.deleteContractDetail(contractForm.getId());

      for (int i = 0; i < contractDetailTemps.size(); i++) {
        ContractDetail contractDetailTemp = new ContractDetail();
        contractDetailTemp = (ContractDetail)contractDetailTemps.get(i);
        contractCost = contractCost.add(contractDetailTemp.getCostValue());
        this.contractDetailDAO.insertContractDetail(contractDetailTemp);
      }

      contract = new Contract();
      contract.setId(contractForm.getId());
      contract.setContractCost(contractCost);
      if ((newContract.getBackCost() == null) || (newContract.getBackCost().compareTo(new BigDecimal(0)) <= 0))
        contract.setReceivable(contractCost);
      else {
        contract.setReceivable(contractCost.subtract(newContract.getBackCost()));
      }
      this.contractDAO.updateContractByDynamic(contract);

      this.contractTempDAO.deleteContractTempByContractId(contractForm.getId());
      this.contractDetailTempDAO.deleteContractDetailTempByContractId(contractForm.getId());

      if ((!StringUtils.isEmpty(realPath)) && 
        (multipartFile != null) && (!multipartFile.isEmpty())) {
        String fileName = multipartFile.getOriginalFilename();
        String storedPath = getStoredPath(realPath, newContract.getCustomerId(), newContract.getId()) + 
          System.getProperty("file.separator") + fileName;
        boolean result2 = false;
        result2 = FileUtils.saveFile(storedPath, multipartFile);
        if (result2) {
          SystemFile systemFile = new SystemFile();
          systemFile.setFileName(fileName);
          systemFile.setFileType(multipartFile.getContentType());

          systemFile.setPath(getStoredRelativePath(newContract.getCustomerId(), newContract.getId()) + System.getProperty("file.separator"));
          systemFile.setPersonId(newContract.getApplyPersonId());
          systemFile.setRelatedId(newContract.getId());
          systemFile.setRelatedTable("contract");
          systemFile.setSize(multipartFile.getSize()+"");
          systemFile.setUploadDate(new Date());
          this.systemFileDAO.insertSystemFile(systemFile);
        }
      }
      return true;
    }
    return false;
  }

  public boolean deleteAdded(String realPath, Integer addedId) {
    if (addedId == null) return false;
    if (StringUtils.isEmpty(realPath)) return false;
    boolean result = false;
    SystemFile systemFile = new SystemFile();
    systemFile = this.systemFileDAO.getSystemFile(addedId);
    if (systemFile == null) return false;
    File file = new File(realPath + systemFile.getPath() + systemFile.getFileName());
    if (file.exists()) {
      result = file.delete();
    }
    this.systemFileDAO.deleteSystemFile(addedId);
    return result;
  }

  public boolean deleteContractAndDetail(Integer contractId) {
    if (contractId == null) return false;
    this.contractDAO.deleteContract(contractId);
    this.contractDetailDAO.deleteContractDetail(contractId);
    this.contractTempDAO.deleteContractTempByContractId(contractId);
    this.contractDetailDAO.deleteContractDetail(contractId);
    return true;
  }

  public String getStoredPath(String basePath, Integer customerId, Integer contractId)
  {
    String storedPath = basePath + "upload" + System.getProperty("file.separator") + 
      "contract" + System.getProperty("file.separator") + 
      customerId + "_" + contractId;
    File file = new File(storedPath);
    if ((file.exists()) && (file.isDirectory()))
    {
      return storedPath;
    }
    file.mkdirs();
    return storedPath;
  }

  public String getStoredRelativePath(Integer customerId, Integer contractId)
  {
    String storedPath = "upload" + System.getProperty("file.separator") + 
      "contract" + System.getProperty("file.separator") + 
      customerId + "_" + contractId;
    File file = new File(storedPath);
    if ((file.exists()) && (file.isDirectory()))
    {
      return storedPath;
    }
    file.mkdirs();
    return storedPath;
  }

  public boolean isFileExists(String basePath, String fullPath, Integer customerId, Integer contractId, String fileName)
  {
    Calendar calendar = Calendar.getInstance();
    String fullPathName = "";
    if (StringUtils.isEmpty(fullPath))
      fullPathName = basePath + "upload" + System.getProperty("file.separator") + 
        "contract" + System.getProperty("file.separator") + 
        customerId + "_" + contractId + System.getProperty("file.separator") + 
        fileName;
    else {
      fullPathName = fullPath + fileName;
    }

    File file = new File(fullPathName);
    return file.exists();
  }

  private List readExcelContractContent(String excelPath, Integer currentUserId)
  {
    POIFSFileSystem fileSystem = null;
    HSSFWorkbook workbook = null;
    HSSFSheet sheet = null;
    HSSFRow row = null;
    FileInputStream fileInputStream = null;
    List logs = new ArrayList();
    try {
      fileInputStream = new FileInputStream(new File(excelPath));
      fileSystem = new POIFSFileSystem(fileInputStream);
      workbook = new HSSFWorkbook(fileSystem);
      sheet = workbook.getSheetAt(0);
      int rowNum = sheet.getLastRowNum();
      row = sheet.getRow(0);
      int colNum = row.getPhysicalNumberOfCells();
      for (int i = 1; i <= rowNum; i++) {
        row = sheet.getRow(i);
        int result = 0;
        String[] colContents = new String[40];

        Contract contract = new Contract();
        colContents[0] = ExcelUtils.getStringCellValue(row.getCell((short)0)).trim();
        if (!StringUtils.isEmpty(colContents[0]))
          contract.setContractCode(colContents[0]);
        else {
          result = 1;
        }
        colContents[1] = ExcelUtils.getStringCellValue(row.getCell((short)1)).trim();
        if (!StringUtils.isEmpty(colContents[1]))
          contract.setCustomerName(colContents[1]);
        else {
          result = 3;
        }
        colContents[2] = ExcelUtils.getStringCellValue(row.getCell((short)2)).trim();
        if (!StringUtils.isEmpty(colContents[2]))
          contract.setContractName(colContents[2]);
        else
          result = 5;
        try
        {
          colContents[3] = ExcelUtils.getDateCellValue(row.getCell((short)3)).trim();
          if (!StringUtils.isEmpty(colContents[3]))
            contract.setContractDate(DateUtils.stringDateConvertDate(colContents[3], "yyyy-MM-dd"));
        }
        catch (Exception ex) {
          result = 6;
        }
        colContents[4] = ExcelUtils.getStringCellValue(row.getCell((short)4)).trim();
        if (!StringUtils.isEmpty(colContents[4]))
          contract.setSalePerson(colContents[4]);
        else {
          result = 7;
        }

        ContractDetail[] contractDetails = new ContractDetail[4];
        colContents[5] = ExcelUtils.getStringCellValue(row.getCell((short)5)).trim();
        if (!StringUtils.isEmpty(colContents[5])) {
          contractDetails[0] = new ContractDetail();

          contractDetails[0].setPurchaseDesc(colContents[5]);

          colContents[6] = ExcelUtils.getStringCellValue(row.getCell((short)6)).trim();
          if (!StringUtils.isEmpty(colContents[6])) {
            contractDetails[0].setUnit(colContents[6]);
          }
          colContents[7] = ExcelUtils.getStringCellValue(row.getCell((short)7)).trim();
          if (!StringUtils.isEmpty(colContents[7])) {
            contractDetails[0].setPrice(NumberUtils.getBigDecimal(colContents[7]));
          }
          colContents[8] = ExcelUtils.getStringCellValue(row.getCell((short)8)).trim();
          if (!StringUtils.isEmpty(colContents[8]))
            contractDetails[0].setNum(Integer.valueOf(NumberUtils.parseInteger(colContents[8])));
          else {
            result = 12;
          }
          colContents[9] = ExcelUtils.getStringCellValue(row.getCell((short)9)).trim();
          if (!StringUtils.isEmpty(colContents[9]))
            contractDetails[0].setCostValue(NumberUtils.getBigDecimal(colContents[9]));
          else {
            result = 13;
          }
          colContents[10] = ExcelUtils.getStringCellValue(row.getCell((short)10)).trim();
          if (!StringUtils.isEmpty(colContents[10]))
            contractDetails[0].setDiscount(NumberUtils.getBigDecimal(colContents[10]));
          else {
            result = 14;
          }
          colContents[11] = ExcelUtils.getStringCellValue(row.getCell((short)11)).trim();
          if (!StringUtils.isEmpty(colContents[11])) {
            contractDetails[0].setCosts(NumberUtils.getBigDecimal(colContents[11]));
          }
          colContents[12] = ExcelUtils.getStringCellValue(row.getCell((short)12)).trim();
          if (!StringUtils.isEmpty(colContents[12]))
            contractDetails[0].setProssProfit(NumberUtils.getBigDecimal(colContents[12]));
        }
        else {
          result = 11;
        }

        colContents[13] = ExcelUtils.getStringCellValue(row.getCell((short)13)).trim();
        if (!StringUtils.isEmpty(colContents[13])) {
          contractDetails[1] = new ContractDetail();

          contractDetails[1].setPurchaseDesc(colContents[13]);

          colContents[14] = ExcelUtils.getStringCellValue(row.getCell((short)14)).trim();
          if (!StringUtils.isEmpty(colContents[14])) {
            contractDetails[1].setUnit(colContents[14]);
          }
          colContents[15] = ExcelUtils.getStringCellValue(row.getCell((short)15)).trim();
          if (!StringUtils.isEmpty(colContents[15])) {
            contractDetails[1].setPrice(NumberUtils.getBigDecimal(colContents[15]));
          }
          colContents[16] = ExcelUtils.getStringCellValue(row.getCell((short)16)).trim();
          if (!StringUtils.isEmpty(colContents[16]))
            contractDetails[1].setNum(Integer.valueOf(NumberUtils.parseInteger(colContents[16])));
          else {
            result = 22;
          }
          colContents[17] = ExcelUtils.getStringCellValue(row.getCell((short)17)).trim();
          if (!StringUtils.isEmpty(colContents[17]))
            contractDetails[1].setCostValue(NumberUtils.getBigDecimal(colContents[17]));
          else {
            result = 23;
          }
          colContents[18] = ExcelUtils.getStringCellValue(row.getCell((short)18)).trim();
          if (!StringUtils.isEmpty(colContents[18]))
            contractDetails[1].setDiscount(NumberUtils.getBigDecimal(colContents[18]));
          else {
            result = 24;
          }
          colContents[19] = ExcelUtils.getStringCellValue(row.getCell((short)19)).trim();
          if (!StringUtils.isEmpty(colContents[19])) {
            contractDetails[1].setCosts(NumberUtils.getBigDecimal(colContents[19]));
          }
          colContents[20] = ExcelUtils.getStringCellValue(row.getCell((short)20)).trim();
          if (!StringUtils.isEmpty(colContents[20])) {
            contractDetails[1].setProssProfit(NumberUtils.getBigDecimal(colContents[20]));
          }

        }

        colContents[21] = ExcelUtils.getStringCellValue(row.getCell((short)21)).trim();
        if (!StringUtils.isEmpty(colContents[21])) {
          contractDetails[2] = new ContractDetail();

          contractDetails[2].setPurchaseDesc(colContents[21]);

          colContents[22] = ExcelUtils.getStringCellValue(row.getCell((short)22)).trim();
          if (!StringUtils.isEmpty(colContents[22])) {
            contractDetails[2].setUnit(colContents[22]);
          }
          colContents[23] = ExcelUtils.getStringCellValue(row.getCell((short)23)).trim();
          if (!StringUtils.isEmpty(colContents[23])) {
            contractDetails[2].setPrice(NumberUtils.getBigDecimal(colContents[23]));
          }
          colContents[24] = ExcelUtils.getStringCellValue(row.getCell((short)24)).trim();
          if (!StringUtils.isEmpty(colContents[24]))
            contractDetails[2].setNum(Integer.valueOf(NumberUtils.parseInteger(colContents[24])));
          else {
            result = 32;
          }
          colContents[25] = ExcelUtils.getStringCellValue(row.getCell((short)25)).trim();
          if (!StringUtils.isEmpty(colContents[25]))
            contractDetails[2].setCostValue(NumberUtils.getBigDecimal(colContents[25]));
          else {
            result = 33;
          }
          colContents[26] = ExcelUtils.getStringCellValue(row.getCell((short)26)).trim();
          if (!StringUtils.isEmpty(colContents[26]))
            contractDetails[2].setDiscount(NumberUtils.getBigDecimal(colContents[26]));
          else {
            result = 34;
          }
          colContents[27] = ExcelUtils.getStringCellValue(row.getCell((short)27)).trim();
          if (!StringUtils.isEmpty(colContents[27])) {
            contractDetails[2].setCosts(NumberUtils.getBigDecimal(colContents[27]));
          }
          colContents[28] = ExcelUtils.getStringCellValue(row.getCell((short)28)).trim();
          if (!StringUtils.isEmpty(colContents[28])) {
            contractDetails[2].setProssProfit(NumberUtils.getBigDecimal(colContents[28]));
          }

        }

        colContents[29] = ExcelUtils.getStringCellValue(row.getCell((short)29)).trim();
        if (!StringUtils.isEmpty(colContents[29])) {
          contractDetails[3] = new ContractDetail();

          contractDetails[3].setPurchaseDesc(colContents[29]);

          colContents[30] = ExcelUtils.getStringCellValue(row.getCell((short)30)).trim();
          if (!StringUtils.isEmpty(colContents[30])) {
            contractDetails[3].setUnit(colContents[30]);
          }
          colContents[31] = ExcelUtils.getStringCellValue(row.getCell((short)31)).trim();
          if (!StringUtils.isEmpty(colContents[31])) {
            contractDetails[3].setPrice(NumberUtils.getBigDecimal(colContents[31]));
          }
          colContents[32] = ExcelUtils.getStringCellValue(row.getCell((short)32)).trim();
          if (!StringUtils.isEmpty(colContents[32]))
            contractDetails[3].setNum(Integer.valueOf(NumberUtils.parseInteger(colContents[32])));
          else {
            result = 42;
          }
          colContents[33] = ExcelUtils.getStringCellValue(row.getCell((short)33)).trim();
          if (!StringUtils.isEmpty(colContents[33]))
            contractDetails[3].setCostValue(NumberUtils.getBigDecimal(colContents[33]));
          else {
            result = 43;
          }
          colContents[34] = ExcelUtils.getStringCellValue(row.getCell((short)34)).trim();
          if (!StringUtils.isEmpty(colContents[34]))
            contractDetails[3].setDiscount(NumberUtils.getBigDecimal(colContents[34]));
          else {
            result = 44;
          }
          colContents[35] = ExcelUtils.getStringCellValue(row.getCell((short)35)).trim();
          if (!StringUtils.isEmpty(colContents[35])) {
            contractDetails[3].setCosts(NumberUtils.getBigDecimal(colContents[35]));
          }
          colContents[36] = ExcelUtils.getStringCellValue(row.getCell((short)36)).trim();
          if (!StringUtils.isEmpty(colContents[36])) {
            contractDetails[3].setProssProfit(NumberUtils.getBigDecimal(colContents[36]));
          }

        }

        if (result == 0) {
          result = insertContract(currentUserId, contract, contractDetails);
        }
        Log log = new Log();
        log.setId(Integer.valueOf(i + 1));
        log.setReason(result+"");
        logs.add(log);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      try
      {
        if (fileInputStream != null)
          fileInputStream.close();
      }
      catch (IOException e1) {
        e1.printStackTrace();
      }
    }
    catch (IOException e)
    {
      e.printStackTrace();
      try
      {
        if (fileInputStream != null)
          fileInputStream.close();
      }
      catch (IOException e1) {
        e1.printStackTrace();
      }
    }
    finally
    {
      try
      {
        if (fileInputStream != null)
          fileInputStream.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
    return logs;
  }

  private int insertContract(Integer currentUserId, Contract contract, ContractDetail[] contractDetails)
  {
    int success = 90;
    if (currentUserId == null) return success;
    if (contract == null) return success;
    if ((contractDetails == null) || (contractDetails.length <= 0) || 
      (contractDetails[0] == null)) return success;
    Contract tempContract = new Contract();
    tempContract = this.contractDAO.getContractByContractCode(contract.getContractCode());
    if (tempContract != null) return 2;

    BigDecimal contractCost = new BigDecimal(0);
    Customer customer = new Customer();
    customer.setCustomerName(contract.getCustomerName());
    List customers = new ArrayList();
    customers = this.customerDAO.getCustomersByDynamic(customer);
    if ((customers == null) || (customers.size() <= 0)) return 4;

    Users user = new Users();
    user = this.userDAO.getUserByUserName(contract.getSalePerson());
    if (user == null) return 8;

    contract.setCustomerId(((Customer)customers.get(0)).getId());
    contract.setSalePersonId(user.getId());
    contract.setAging(Integer.valueOf(0));
    contract.setApplyPersonId(currentUserId);
    contract.setBackCost(contractCost);
    contract.setBackCostNum(Integer.valueOf(0));
    contract.setContractCost(contractCost);
    contract.setCreateDate(new Date());
    contract.setReceivable(contractCost);
    contract.setStatus("1");
    this.contractDAO.insertContract(contract);
    Contract newContract = new Contract();
    newContract = this.contractDAO.getContractByContractCode(contract.getContractCode());
    if (newContract == null) return success;
    success = 92;
    Integer contractId = newContract.getId();

    insertContractUpdateHistory(newContract, currentUserId, 0);

    String updateHistoryCode = new Long(new Date().getTime()).toString();
    int num = 1;
    for (int i = 0; i < contractDetails.length; i++) {
      if (contractDetails[i] != null) {
        String purchaseDesc = contractDetails[i].getPurchaseDesc();
        BigDecimal number = new BigDecimal(contractDetails[i].getNum().intValue());
        BigDecimal price = contractDetails[i].getPrice();
        BigDecimal costValue = contractDetails[i].getCostValue();
        BigDecimal discount = contractDetails[i].getDiscount();
        BigDecimal cost = contractDetails[i].getCosts();
        BigDecimal prossProfit = contractDetails[i].getProssProfit();
        if ((StringUtils.isEmpty(purchaseDesc)) || (number == null) || 
          (discount == null) || (discount.compareTo(new BigDecimal(0)) <= 0)) continue;
        discount = discount.divide(new BigDecimal(100), 2, 4);
        if ((price != null) && (price.compareTo(new BigDecimal(0)) > 0)) {
          costValue = price.multiply(number).multiply(discount);
        }

        if ((costValue == null) || (costValue.compareTo(new BigDecimal(0)) <= 0))
          continue;
        if ((cost == null) && (prossProfit == null)) {
          cost = costValue.divide(new BigDecimal(2), 2, 4);
          prossProfit = costValue.subtract(cost);
        } else if (cost == null) {
          cost = costValue.subtract(prossProfit);
        } else if (prossProfit == null) {
          prossProfit = costValue.subtract(cost);
        }

        contractDetails[i].setDetailCode(num+"");
        contractDetails[i].setContractId(contractId);
        contractDetails[i].setCostValue(costValue);
        contractDetails[i].setCosts(cost);
        contractDetails[i].setProssProfit(prossProfit);
        this.contractDetailDAO.insertContractDetail(contractDetails[i]);

        contractCost = contractCost.add(contractDetails[i].getCostValue());

        insertContractDetailUpdateHistory(updateHistoryCode, contractDetails[i], 0);
        num++;
      }

    }

    Contract paraContract = new Contract();
    paraContract.setId(contractId);
    paraContract.setContractCost(contractCost);
    paraContract.setReceivable(contractCost);
    this.contractDAO.updateContractByDynamic(paraContract);

    customer = new Customer();
    customer = this.customerDAO.getCustomerById(newContract.getCustomerId());
    if (customer != null) {
      Customer paraCustomer = new Customer();
      paraCustomer.setId(customer.getId());
      paraCustomer.setIsFollow("0");
      paraCustomer.setIsShare("0");

      paraCustomer.setUpdateSaleStageDate(new Date());

      paraCustomer.setSaleStageId(Integer.valueOf(0));
      this.customerDAO.updateCustomer(paraCustomer);
      this.customerShareDAO.deleteCustomerShare(customer.getId());

      this.customerShareDAO.insertCustomerShare(customer.getId(), customer.getSalePersonId(), "1");

      this.saleRecordDAO.updateSaleRecordStatusByCustomerId(customer.getId(), "0", "1");
    }

    this.warningInfoDAO.insertAuditWarningInfoForContract(newContract);
    return success;
  }

  private boolean insertContractUpdateHistory(Contract contract, Integer userId, int sign)
  {
    if ((contract == null) || (contract.getId() == null)) return false;
    if (sign == 1)
      contract.setIsPrimitive("0");
    else {
      contract.setIsPrimitive("1");
    }
    contract.setContractId(contract.getId());
    contract.setUpdatePersonId(userId);
    contract.setUpdateDate(new Date());
    this.contractUpdateHistoryDAO.insertContractUpdateHistory(contract);
    return true;
  }

  private boolean insertContractDetailUpdateHistory(String updateHistoryCode, ContractDetail contractDetail, int sign)
  {
    if ((contractDetail == null) || (StringUtils.isEmpty(contractDetail.getDetailCode()))) return false;
    if (contractDetail.getContractId() == null) return false;
    ContractDetail cDetail = new ContractDetail();
    cDetail = this.contractDetailDAO.getContractDetailByContractIdAndDetailCode(contractDetail.getContractId(), contractDetail.getDetailCode());
    if (sign == 1)
      cDetail.setIsPrimitive("0");
    else {
      cDetail.setIsPrimitive("1");
    }
    cDetail.setContractDetailId(contractDetail.getId());
    cDetail.setUpdateHistoryCode(updateHistoryCode);
    this.contractDetailUpdateHistoryDAO.insertContractDetailUpdateHistory(cDetail);
    return true;
  }

  private boolean insertContractTemp(Integer contractId)
  {
    if (contractId == null) return false;
    Contract contract = new Contract();
    contract = this.contractDAO.getContractById(contractId);
    if (contract == null) return false;

    this.contractTempDAO.deleteContractTempByContractId(contractId);

    contract.setContractId(contract.getId());
    this.contractTempDAO.insertContractTemp(contract);

    this.contractDetailTempDAO.deleteContractDetailTempByContractId(contractId);
    List contractDetails = new ArrayList();
    contractDetails = this.contractDetailDAO.getContractDetailsByContractId(contractId);
    if (contractDetails != null) {
      for (int i = 0; i < contractDetails.size(); i++) {
        ContractDetail contractDetail = new ContractDetail();
        contractDetail = (ContractDetail)contractDetails.get(i);
        contractDetail.setContractDetailId(contractDetail.getId());
        this.contractDetailTempDAO.insertContractDetailTemp(contractDetail);
      }
    }
    return true;
  }

  public List getContractByCustomerId(Integer customerId) {
    Contract contract = new Contract();
    contract.setCustomerId(customerId);
    return this.contractDAO.getContractByCustomerId(contract);
  }

  public boolean updateContractByDynamic(Contract contract)
  {
    return this.contractDAO.updateContractByDynamic(contract);
  }
  

  public CodeStore getCodeStoreByType(String type)
  {
	  return this.contractDAO.getCodeStoreByType(type);
  }  
  
  public List<ContractCase> getContractCaseListByCaseCode(String caseCode)
  {
	  return this.contractDAO.getContractCaseListByCaseCode(caseCode);
  }
  
  public boolean deleteContractCase(String delContractCaseId)
  {
	 return this.contractDAO.deleteContractCase(delContractCaseId); 
  }
  public Long selectCaseSeq(){
	  try {
		  return contractCaseDAO.selectCaseSeq();
	} catch (Exception e) {
		throw new RuntimeException();
	}
  }
	public List<ContractCase> getContractCasesByContractCode(String contractCode)
	{
		return contractCaseDAO.getContractCasesByContractCode(contractCode);
	}
	
	public List<Contract> getContractListBySameCustomer(Integer contractId)
	{
		Contract contract = contractDAO.getContractById(contractId);
		Contract newContract = new Contract();
		newContract.setCustomerId(contract.getCustomerId());
		List<Contract> contractList = contractDAO.getContractByCustomerId(newContract);
		
		return contractList;
	}
	
	public List<ContractCase> getContractCaseListByIds(String[] caseIds)
	{
		return contractCaseDAO.getContractCaseListByIds(caseIds);
	}
	
	public boolean insertCost(CostForm costForm)
	{
		String[] contractCaseId = costForm.getContractCaseIds().split("/");
		
		CostManage costManage = new CostManage();
		costManage.setCostId(costForm.getCostId());
		costManage.setCostType(costForm.getCostType());
		costManage.setPaymentAccount(costForm.getPaymentAccount());
		costManage.setPersonId(costForm.getPersonId());
		costManage.setPaymentDate(costForm.getPaymentDate());
		costManage.setStatus(0);
		Integer costId = contractCaseDAO.insertCost(costManage);		
		
		for(int i=0; i<contractCaseId.length; i++)
		{
			ContractCase cc = contractCaseDAO.getContractCasesById(Integer.parseInt(contractCaseId[i]));

			if(("officialCost").equals(costManage.getCostType()))
			{
				cc.setOfficialCostId(costId);
				cc.setOfficialCostStatus(0);
			}
			if(("operationCost").equals(costManage.getCostType()))
			{
				cc.setOperationCostId(costId);
				cc.setOperationCostStatus(0);
			}	
			
			contractCaseDAO.updateContractCase(cc);
		}
		
		return true;
	}
	
	public List<CostManage> getCostManageListByType(String costType)
	{
		CostManage manage = new CostManage();
		manage.setCostType(costType);
		manage.setStatus(0);
		return contractCaseDAO.getCostManageListByDynamica(manage);
	}
	
	public List<CostManage> getCostManageListByCostId(String costId)
	{
		CostManage manage = new CostManage();
		manage.setCostId(costId);
		return contractCaseDAO.getCostManageListByDynamica(manage);
	}	
	
	public Integer updateCostManage(Integer id)
	{
		CostManage manage = contractCaseDAO.getCostManageById(id);
		manage.setStatus(1);
		contractCaseDAO.updateCostManage(manage);
		
		if(("officialCost").equals(manage.getCostType()))
		{
			for(ContractCase cc : manage.getOfficalCCList())
			{
				cc.setOfficialCostStatus(1);
				contractCaseDAO.updateContractCase(cc);
			}
		}
		if(("operationCost").equals(manage.getCostType()))
		{
			for(ContractCase cc : manage.getOperationCCList())
			{
				cc.setOperationCostStatus(1);
				contractCaseDAO.updateContractCase(cc);
			}
		}		
		return 1;
	}	
}